<template>
    <div>
        <div class="upload">
            <img v-if="url" :src="'http://localhost:3003'+url" alt="">
            <div v-else>+</div>
            <van-uploader 
                class="uploader"
                :after-read="afterRead"
                preview-image
            />
        </div>
        <!-- <img :src="base64" alt=""> -->
        <van-button type="primary" @click="handleUpdate">保存</van-button>
    </div>
</template>

<script>
    import request from '@/utils/request'
    import {mapState} from 'vuex'
    import {userUpdate} from '@/api/user'
    export default {
        data() {
            return {
                base64: '',
                url:'' //预览头像
            }
        },
        computed: {
            ...mapState({
                userInfo:state=>state.my.userInfo
            })
        },
        created () {
            let {avatar} = this.userInfo
            if(avatar){
                this.url = avatar
            }
        },
        methods: {
            afterRead(file) {
                // 此时可以自行将文件上传至服务器
                // console.log(file);
                
                let formData = new FormData() 
                formData.append('avatar', file.file) //将文件资源整理为表单对象格式
                console.log(formData)
                request.post('/node/users/upload', formData, {
                    headers: {
                        'enctype': 'multipart/form-data'
                    }
                }).then(res => {
                    console.log(res.data)
                    let {url} = res.data.data
                    this.url = url
                })
            },
            handleUpdate(){
                let {_id} = this.userInfo
                userUpdate(_id,{avatar:this.url}).then(res=>{ //更新数据库用户信息
                    this.$store.commit('my/initInfoMut',{ //更新本地用户信息
                        ...this.userInfo,  //旧用户信息
                        avatar:this.url  //新增用户头像
                    })
                })
            }
        },
    }
</script>

<style lang="less" scoped>
.upload{
    width: 80px;
    height: 80px;
    border: 1px dashed #333;
    display: flex;
    align-items: center;
    justify-content: center;
    position: relative;
    font-size: 30px;
    img{
        width: 100%;
        height: 100%;
    }
    .uploader{
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        opacity: 0;
    }
}
</style>